﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace TimeCapsule
{
	public class Member
	{
		private int _idx, _role;
		private string _id, _email, _name, _phone, _address, _key;
		private bool _isDisabled, _isAdmin;
		private DateTime _regDate, _lastLogin;
		private const string DELIM = "\t";
		
		public int Idx { get { return _idx; }  set { _idx = value; } }
		public Role Role { get { return (Role)_role; } set { _role = (int)value; } }
		public string Id { get { return _id; } set { _id = value; } }
		public string Email { get { return _email; } set { _email = value; } }
		public string Name { get { return _name; } set { _name = value; } }
		public string Phone { get { return _phone; } set { _phone = value; } }
		public string Address { get { return _address; } set { _address = value; } }
		public string key { get { return _key; } set { _key = value; } }
		public bool isDisabled { get { return _isDisabled; } set { _isDisabled = value; } }
		public bool isAdmin { get { return _isAdmin; } set { _isAdmin = value; } }
		public DateTime regDate { get { return _regDate; } set { _regDate = value; } }
		public DateTime lastLogin { get { return _lastLogin; } set {_lastLogin = value; } }
		
		public Member()
		{
			if( HttpContext.Current.User.Identity.IsAuthenticated )
			{
				HttpCookie ck = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
				if( ck != null )
				{
					string encTicket = ck.Value;
					FormsAuthenticationTicket decTicket = FormsAuthentication.Decrypt(encTicket);
					
					if( decTicket != null )
						Init( decTicket.UserData );
					else
						Init();
				}
				else
					Init();
			}
			else
				Init();
		}
		
		public Member(int idx, string mail, string key, string name, int role, string phone, string address, DateTime adddate, DateTime lastlogin)
		{
			Init(idx, mail, key, name, role, phone, address, adddate, lastlogin);
		}
		
		private void Init()
		{
			_idx = -1;
			_email = "";
			_role = 0;
			_key = "";
			_name = "";
			_phone = "";
			_address = "";
			_regDate = DateTime.MinValue;
			_lastLogin = DateTime.MinValue;
		}
		
		private void Init(string data)
		{
			if( string.IsNullOrEmpty(data) )
			{
				Init();
				return;
			}
			string[] arr = data.Split(new string[] { DELIM }, StringSplitOptions.None );
			_email = arr[0];
			_role = int.Parse(arr[1]);
			_key = arr[2];
			_name = arr[3];
			_phone = arr[4];
			_address = arr[5];
			_regDate = DateTime.Parse(arr[6]);
			_lastLogin = DateTime.Parse(arr[7]);
			_idx = int.Parse(arr[8]);
			if( HttpContext.Current.Session == null )
			{
				Init();
				return;
			}
			if( ( HttpContext.Current.Session["key"] != null && HttpContext.Current.Session["key"].ToString() != _key ) || !Util.decryptKey(_key) )
				Init();
		}
		
		private void Init(int idx, string mail, string key, string name, int role, string phone, string address, DateTime adddate, DateTime lastlogin)
		{
			_idx = idx;
			_email = mail;
			_role = role;
			_key = key;
			_name = name;
			_phone = phone;
			_address = address;
			_regDate = adddate;
			_lastLogin = lastlogin;
		}

		public override string ToString()
		{
			return _email + DELIM + _role + DELIM + _key + DELIM + _name + DELIM + _phone + DELIM + _address + DELIM + _regDate + DELIM + _lastLogin + DELIM + _idx;
		}
		
		public void FlushLoginTicket()
		{
			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
				1, _email, DateTime.Now, DateTime.Now.AddMinutes(60), false, this.ToString() );
			string encTicket = FormsAuthentication.Encrypt(ticket);
			HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
			
			HttpContext.Current.Session.Add("key", _key);
			HttpContext.Current.Response.Cookies.Add(ck);
		}
		
		public static Member Login(string mail, string password)
		{
			dbAccess da = new dbAccess();
			DataSet ds;
			bool valid = da.Login(mail, password, out ds);
			if ( valid )
			{
				string sess = Util.generateEncrytedKey();
				int idx = int.Parse(ds.Tables[0].Rows[0]["Idx"].ToString());
				string name = ds.Tables[0].Rows[0]["name"].ToString();
				int role = int.Parse( ds.Tables[0].Rows[0]["role"].ToString() );
				string phone = ds.Tables[0].Rows[0]["phone"].ToString();
				string address = ds.Tables[0].Rows[0]["address"].ToString();
				DateTime adddate = DateTime.Parse(ds.Tables[0].Rows[0]["adddate"].ToString());
				DateTime lastlogin = DateTime.Now;
				Member mb = new Member(idx, mail, sess, name, role, phone, address, adddate, lastlogin);
				mb.FlushLoginTicket();
				return mb;
			} 
			else
			{
				Member mb = new Member();
				return mb;
			}
		}
		
		public void LogOut()
		{
			Logoff(true);
		}
		
		public static void Logoff(bool token)
		{
			HttpCookie ck = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
			if( ck != null )
			{
				ck.Value = null;
				ck.Expires = DateTime.MinValue;
				HttpContext.Current.Response.Cookies.Set(ck);
				HttpContext.Current.Session.RemoveAll();
			}
		}
	}
}